<template>
	<view class="card-body" :style="[AppSkinVar]">
		<view>
			<view class="header-box bg-white" v-if="cartProductAll">
				<view class="manage-box e-flex e-flex-between">
					<view class="e-font-26 c-b2">
						{{ $t('cart.共') }}
						<text class="c-primary e-p-l-6 e-p-r-6">{{ cartProductAll }}</text>
						{{ $t('classify.件') }}
					</view>
					<view class="btn" @tap="setManage">{{ $t('common.' + (isManage ? '完成' : '编辑')) }}</view>
				</view>
			</view>
			<view>
				<view class="goods-box e-p-t-20">
					<view class="e-m-b-20" v-for="(item, index) in list" :key="index">
						<goods-card cardType="1" v-model:goodsList="item.baskets" :goodsKeys="goodsKeys"
							:store="item.store" goodsLink="/pages/classify/goods/info/index" :logoShow="false"
							:isRadio="true" :isEditCount="true" :isReselection="true" :isLimit="false"
							:cartCheck="cartCheck" :isCartEdit="isManage" @reselection="reselection"
							@editCount="editCount" @checkStore="checkStore" @checkCart="checkCart">
							<template #deduction="{ goods }">
								<view class="bg-f7 e-p-20" v-if="goods.formJson">
									<goods-layout-form-popup replyInfo :formJson="goods.formJson" :subType="2"
										:price="goods.deputyMoney" :number="goods.commodityCount"
										@edit="getCart"></goods-layout-form-popup>
								</view>
							</template>
						</goods-card>
					</view>
				</view>
				<empty :text="$t(isLogin ? 'cart.暂无商品' : 'common.未登录')" :icon="$staticPath('default_img.png')"
					:show="emptyShow">
					<view class="button-box e-p-t-60" v-if="!isLogin">
						<e-button size="large" type="primary" shape="circle" :text="$t('common.去登录')" @click="
								$goLogin({
									isShowModal: false
								})
							"></e-button>
					</view>
				</empty>
			</view>
			<view v-if="cartInvalidGoodsList && cartInvalidGoodsList.length">
				<view>
					<view class="invalid-manage-box e-flex e-flex-between">
						<text>{{ $t('cart.已失效商品') }}</text>
						<view class="btn" @tap="setInvalidManage">{{ $t('common.' + (isInvalidManage ? '完成' : '编辑')) }}
						</view>
					</view>
				</view>
				<view>
					<view class="goods-box">
						<invalid-goods :isRadio="isInvalidManage" :list="cartInvalidGoodsList"
							:invalidCheck="invalidCheck" @checkInvalid="checkInvalid"></invalid-goods>
					</view>
				</view>
			</view>
			<template v-if="cartProductAll || (cartInvalidGoodsList && cartInvalidGoodsList.length)">
				<goods-list class="e-m-t-20" :leftGoodsList="leftList" :rightGoodsList="rightList"></goods-list>
				<load-more :showLoad="showLoad"></load-more>
			</template>

			<view style="height: 236rpx" v-if="isTababr"></view>
			<view style="height: 124rpx" v-else></view>
			<view class="ios-btm"></view>
			<view class="btm-fixed-boxs" v-if="cartProductAll || isInvalidManage">
				<view class="contxt-box e-flex e-flex-between bg-white">
					<view @tap="checkAll">
						<radio class="e-m-r-20" :color="AppSkin.primary" :checked="isAll" @tap.stop="checkAll" />
						<text class="e-font-30">{{ $t('cart.全选') }}</text>
					</view>
					<view class="right-box e-flex">
						<view class="txt-box" v-if="!isManage && !isInvalidManage">
							{{ $t('cart.总计') }}：
							<text class="c-primary">{{ $unitEn }}{{ checkGoodsMoneyTotal }}</text>
						</view>
						<view class="right-box__button e-flex-xy-center" :class="{ 'is-ok': isOk }" @tap="submit">
							<text>
								{{ $t(isManage || isInvalidManage ? 'common.删除' : 'cart.结算')
								}}{{ !isManage && !isInvalidManage && settlementGoodsList.length ? `(${settlementGoodsList.length})` : '' }}
							</text>
						</view>
					</view>
				</view>
				<view style="height: 112rpx" v-if="isTababr"></view>
			</view>
		</view>
		<!-- 规格弹窗 -->
		<sku-popup v-model:checkInfo="reselectionCheckInfo" v-model:goodsNum="skuGoodsNum"
			v-model:info="reselectionGoodsInfo" :maxNumber="skuMaxNumber" :defaultSkuId="skuId"
			:primary="AppSkin.primary" :show="popupShow" @confirm="skuConfirm"
			@close="() => (popupShow = false)"></sku-popup>
	</view>
</template>
<script lang="ts">
	import { defineComponent } from 'vue';
	import layoutMainPageMixIn from '../../utils/layoutMainPageMixIn';
	// 购买商品权限前的校验，包含一个verificationPurchasePermission的异步函数，套版项目可根据项目需求改动该文件实现验证购买权限
	import purchaseGoodsMixIn from '@/common/mixin/purchaseGoodsMixIn';
	export default defineComponent({
		// #ifdef MP-WEIXIN
		// 将自定义节点设置成虚拟的，更加接近Vue组件的表现
		options: {
			virtualHost: true
		},
		// #endif
		mixins: [layoutMainPageMixIn, purchaseGoodsMixIn]
	});
</script>
<script setup lang="ts">
	import { computed, ref } from 'vue';
	import invalidGoods from './child/invalidGoods.vue';
	import skuPopup from './child/skuPopup.vue';
	import { throttle, debounce } from '@/common/utils';
	import { postDleCart, postEditCart, getGoodsSkuDetail, getPreferenceGoodsList, getGoodsDetail } from '@/common/request/api';
	import type { GoodsSkuDetail, CartGoodsItem, CartItem } from '@/common/request/api';
	import { useTabbar } from '../../utils/customTabbar';
	import { useCurrentInstance, useWaterfallsPage } from '@/common/hooks';
	import { useUser, useInit, useShoppingCart } from '@/common/stores';
	import { storeToRefs } from 'pinia';

	const props = defineProps({
		index: {
			type: String,
			required: true
		},
		isTababr: {
			type: Boolean,
			default: true
		}
	});

	const emit = defineEmits(['endRefresh']);

	const ctx = useCurrentInstance();

	const { onShow, onPullDownRefresh, onReachBottom } = useTabbar(props.index);

	const userStore = useUser();
	const ShoppingCartStore = useShoppingCart();

	const { getCart, setCartGoodsList, setCartCheckMap } = ShoppingCartStore;

	const { AppSkin } = storeToRefs(useInit());
	const { isLogin } = storeToRefs(userStore);

	const { cartGoodsList, cartInvalidGoodsList, cartProductAll, checkGoodsMoneyTotal, cartCheckMap } = storeToRefs(ShoppingCartStore);

	const list = computed<CartItem[]>({
		get() {
			return cartGoodsList.value as unknown as CartItem[];
		},
		set(v) {
			setCartGoodsList(v);
		}
	});

	const isManage = ref(false);
	const goodsKeys = {
		price: 'productSku.price',
		image: 'productSku.skuCoverImg',
		name: 'productSku.productName',
		skuId: 'productSku.id',
		skuName: 'productSku.skuSpec',
		qry: 'qry'
	};
	const isInvalidManage = ref(false);
	const invalidCheck = ref<string[]>([]);

	const setManage = () => {
		isManage.value = !isManage.value;
		isInvalidManage.value = false;
	};
	const setInvalidManage = () => {
		isInvalidManage.value = !isInvalidManage.value;
		isManage.value = false;
	};

	// 要修改的商品规格信息
	const reselectionGoodsInfo = ref<GoodsSkuDetail>({
		id: 0,
		productSkus: [],
		productSkuSpecifications: []
	});
	// 选中的规格信息
	const reselectionCheckInfo = ref<GoodsSkuDetail | null>(null);
	const popupShow = ref(false);
	// 修改规格的购物车商品id
	const editId = ref<number | null>(null);

	const {
		showLoad,
		leftList,
		rightList,
		handleQueryPage: getGoodsData,
		handleUpdate,
		handleRefresh
	} = useWaterfallsPage({
		api: getPreferenceGoodsList
	});

	const cartCheck = computed(() => {
		let list : CartGoodsItem[] = [];
		cartCheckMap.value.forEach((item) => list.push(item));
		return list;
	});
	const settlementGoodsList = computed(() => {
		return cartCheck.value.filter((item) => item.productSku.stock > 0).map((item) => item.id);
	});
	const emptyShow = computed(() => {
		if (!isLogin.value) {
			return true;
		} else {
			return !cartProductAll.value && cartInvalidGoodsList.value.length == 0;
		}
	});
	const isOk = computed(() => {
		if (isInvalidManage.value) {
			return !invalidCheck.value.length;
		} else {
			return !cartCheckMap.value.size;
		}
	});
	const isAll = computed(() => {
		let tempNow : string[] = [];
		let allList : string[] = [];
		if (isInvalidManage.value == false && cartProductAll.value) {
			// 编辑正常商品时
			cartGoodsList.value.map((bitem) => {
				bitem.baskets.map((item) => {
					allList.push(item.id);
					if (cartCheckMap.value.has(item.id)) {
						tempNow.push(item.id);
					}
				});
			});
			return tempNow.length == allList.length && allList.length ? true : false;
		} else {
			// 编辑失效商品时
			cartInvalidGoodsList.value.map((item) => {
				allList.push(item.id);
				if (invalidCheck.value.includes(item.id)) {
					tempNow.push(item.id);
				}
			});
			return tempNow.length == allList.length && allList.length ? true : false;
		}
	});

	const checkAll = () => {
		let tempNow : string[] = [];
		let allList : string[] = [];
		if (isInvalidManage.value) {
			// 失效商品全选
			let tempList = invalidCheck.value;
			cartInvalidGoodsList.value.map((item) => {
				allList.push(item.id);
				if (invalidCheck.value.includes(item.id)) {
					tempNow.push(item.id);
				}
			});
			if (tempNow.length == allList.length) {
				tempList = [];
			} else {
				cartInvalidGoodsList.value.map((item) => {
					if (!invalidCheck.value.includes(item.id)) {
						tempList.push(item.id);
					}
				});
			}
			invalidCheck.value = tempList;
		} else {
			// 正常商品全选
			let tempList = new Map(cartCheckMap.value);

			cartGoodsList.value.map((bitem) => {
				bitem.baskets.map((item) => {
					allList.push(item.id);
					if (cartCheckMap.value.has(item.id)) {
						tempNow.push(item.id);
					}
				});
			});
			if (tempNow.length == allList.length) {
				setCartCheckMap(new Map([]));
			} else {
				cartGoodsList.value.map((bitem) => {
					bitem.baskets.map((item) => {
						if (!cartCheckMap.value.has(item.id)) {
							tempList.set(item.id, item);
						}
					});
				});
				setCartCheckMap(tempList);
			}
			getCart();
		}
	};

	// 购物车内不为失效状态的店铺的勾选、取消勾选
	const checkStore = (list : CartGoodsItem[]) => {
		let tempList = new Map(cartCheckMap.value);
		let tempNow : CartGoodsItem[] = [];
		list.map((item) => {
			if (cartCheckMap.value.has(item.id)) {
				tempNow.push(item);
			}
		});
		if (tempNow.length == list.length) {
			tempNow.map((item) => {
				tempList.delete(item.id);
			});
		} else {
			list.map((item) => {
				if (!cartCheckMap.value.has(item.id)) {
					tempList.set(item.id, item);
				}
			});
		}
		setCartCheckMap(tempList);
	};
	// 购物车内不为失效状态的商品的勾选、取消勾选
	const checkCart = (goods : CartGoodsItem) => {
		let tempList = new Map(cartCheckMap.value);
		if (cartCheckMap.value.has(goods.id)) {
			tempList.delete(goods.id);
		} else {
			tempList.set(goods.id, goods);
		}
		setCartCheckMap(tempList);
		getCart();
	};
	// 购物车内为失效状态的商品的勾选、取消勾选
	const checkInvalid = (id : string) => {
		if (invalidCheck.value.find((o) => o == id)) {
			invalidCheck.value.splice(invalidCheck.value.indexOf(id), 1);
		} else {
			invalidCheck.value.push(id);
		}
	};
	const skuGoodsNum = ref(1);
	const skuId = ref('');
	const skuMaxNumber = ref(0);
	const reselection = (productId : string, id : number, number = 1, _skuId ?: string) => {
		editId.value = id;
		skuGoodsNum.value = number;
		if (_skuId) {
			skuId.value = _skuId;
		}
		getGoodsSkuDetail({
			productId
		}).then((res) => {
			reselectionGoodsInfo.value = res.data;
			popupShow.value = true;
		});

		getGoodsDetail({
			id: productId
		}).then((res) => {
			skuMaxNumber.value = res.data.maxNumber || 0;
		});
	};
	// 修改购物车商品规格
	const skuConfirm = (basketCount : number) => {
		popupShow.value = false;
		editId.value &&
			postEditCart(
				{
					skuId: reselectionCheckInfo.value!.id,
					basketCount
				},
				editId.value
			).then(() => {
				getCart();
			});
	};

	const editCount = debounce(function (basketCount : number, id : string) {
		postEditCart(
			{
				basketCount
			},
			id
		).then(() => {
			getCart();
		});
	}, 400);

	const submit = throttle(function () {
		if (isInvalidManage.value) {
			ctx.$showModal({
				content: ctx.$t('cart.确定删除选中的失效商品'),
				success: (res) => {
					if (res.confirm) {
						del(invalidCheck.value.join(','));
					}
				}
			});
		} else {
			if (!cartCheckMap.value.size) {
				ctx.$toastApp(ctx.$t('cart.暂未选择商品'));
				return;
			}
			if (isManage.value) {
				//删除
				del(cartCheck.value.map((item) => item.id).join(','));
			} else {
				//结算

				// 判断是否存在库存不足的商品 即购买量大于库存
				let noStock = false;
				cartCheck.value.some((item) => {
					if (item.basketCount > item.productSku.stock) {
						noStock = true;
						return noStock;
					}
				});
				if (noStock) {
					ctx.$toastApp(ctx.$t('cart.库存不足'));
					return;
				}

				// 有闪送默认闪送，没有就默认配送，再没有就快递
				// 2快递发货 3-闪送 4-核销 5-自提 6-配送
				const _deliveryMode : Array<string[]> = [];
				cartCheck.value.forEach((item) => {
					_deliveryMode.push(item.deliveryMode.split(','));
				});
				let _receivingType;
				_deliveryMode.some((item) => {
					if (item.includes('3')) {
						_receivingType = 3;
						return true;
					}
				});
				if (!_receivingType) {
					let flag = _deliveryMode.some((item) => {
						if (item.includes('6')) {
							_receivingType = 6;
							return true;
						}
					});
					if (!flag) {
						flag = _deliveryMode.some((item) => {
							if (item.includes('5')) {
								_receivingType = 5;
								return true;
							}
						});
					}
					if (!flag) {
						flag = _deliveryMode.some((item) => {
							if (item.includes('2')) {
								_receivingType = 2;
								return true;
							}
						});
					}
				}
				ctx.$goTo('/pages/systemPay/goods/previewOrder', {
					type: 2,
					receivingType: _receivingType,
					basketIds: settlementGoodsList.value.join(',')
				});
			}
		}
	}, 1000);
	const del = (ids : string) => {
		postDleCart(ids).then(() => {
			getCart();
		});
		isInvalidManage.value = false;
	};

	handleRefresh();

	onShow(() => {
		getCart();
	});
	onPullDownRefresh(() => {
		if (isLogin.value) {
			getCart().then(() => {
				emit('endRefresh');
			});
		}
		handleUpdate().then(() => {
			emit('endRefresh');
		});
	});
	onReachBottom(() => {
		getGoodsData();
	});
</script>

<style lang="scss" scoped>
	// .card-body {
	// 	height: calc(100vh - 44px);
	// 	scroll-view {}
	// }
	.c-b2 {
		color: #b2b2b2;
	}

	.header-box {
		position: sticky;
		top: 0;
		left: 0;
		right: 0;
		z-index: $z-index-most;
	}

	.invalid-manage-box,
	.manage-box {
		height: 78rpx;
		font-size: 30rpx;
		padding: 0 40rpx;

		.btn {
			color: #4d4d4d;
		}
	}

	.btm-fixed-boxs {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: #ffffff;
		z-index: $z-index-normal;

		.contxt-box {
			padding: 16rpx 30rpx;

			// height: 124rpx;
			.left-box {
				font-size: 30rpx;
			}

			.right-box {
				.txt-box {
					@include fontH(30, 42);
				}

				&__button {
					width: 218rpx;
					height: 80rpx;
					color: #ffffff;
					font-size: 30rpx;
					background: var(--color-primary);
					border-radius: 40rpx;
					margin-left: 20rpx;
				}
			}
		}
	}

	.goods-box {
		padding: 0 20rpx;

		>view {
			border-radius: 10rpx;

			overflow: hidden;
		}
	}

	.recommend-title {
		padding: 24rpx 0;

		view {
			padding: 0 68rpx;
			color: #303133;

			&::after,
			&::before {
				content: '';
				position: absolute;
				width: 68rpx;
				height: 2rpx;
				background-color: var(--color-primary);
				top: 50%;
			}

			&::after {
				left: -32rpx;
			}

			&::before {
				right: -32rpx;
			}
		}
	}

	.button-box {
		width: 278rpx;
		margin: 0 auto;
	}
</style>